package com.chinasoft.maysham.manager.service.project.impl;

import com.chinasoft.maysham.manager.enums.ProjectType;
import com.chinasoft.maysham.manager.exception.BizException;
import com.chinasoft.maysham.manager.model.Project;
import com.chinasoft.maysham.manager.repo.project.ProjectRepo;
import com.chinasoft.maysham.manager.service.config.ProjectConfigService;
import com.chinasoft.maysham.manager.service.project.ProjectService;
import com.chinasoft.maysham.manager.service.project.ProjectUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class ProjectServiceImpl implements ProjectService {

    @Resource
    private ProjectRepo projectRepo;

    @Resource
    private ProjectUserService projectUserService;

    @Resource
    private ProjectConfigService projectConfigService;

    @Override
    public Project create(Project project, String userId) {
        if (projectRepo.exist(Criteria.where("username").is(project.getName()).and("deleted").is(false))) {
            throw new BizException("名称重复");
        }
        if (project.getType() == null) {
            project.setType(ProjectType.COMMON);
        }
        Project saveProject = new Project();
        BeanUtils.copyProperties(project, saveProject, "id");
        Project save = projectRepo.save(saveProject);
        // 初始化项目成员
        projectUserService.initByProject(save, userId);
        // init project config
        projectConfigService.init(save);
        return save;
    }

    @Override
    public List<Project> list(int page, int size, String userId) {
        return projectRepo.listBy(userId, page, size);
    }

    @Override
    public Project update(Project project, String userId, String projectId) {
        Project dbProject = projectRepo.findById(projectId, Project.class);
        if (dbProject == null) {
            throw new BizException("project not found");
        }
        boolean exist = projectRepo.exist(Criteria.where("username").is(project.getName()).and("deleted").is(false), Project.class);
        if (exist) {
            throw new BizException("project username duplicated");
        }
        dbProject.setName(project.getName());
        dbProject.setDescription(project.getDescription());
        if (!StringUtils.isEmpty(project.getLogo())) {
            dbProject.setLogo(project.getLogo());
        }
        return projectRepo.save(dbProject);
    }

    @Override
    public boolean delete(String projectId, String userId) {
        return projectRepo.deleteById(projectId, Project.class);
    }

    @Override
    public Project queryById(String projectId) {
        return projectRepo.findById(projectId, Project.class);
    }
}
